package dao

import (
	"errors"
	"gorm.io/gorm"
	"product-service/common"
	"product-service/dao/entity"
)

var (
	PmsCategoryBrandRelationDao = &pmsCategoryBrandRelationDao{}
)

type pmsCategoryBrandRelationDao struct {
}

func (this *pmsCategoryBrandRelationDao) FindAll(db *gorm.DB, query *common.PageQuery) ([]*entity.PmsCategoryBrandRelation, int64, error) {
	tx := db.Scopes(Page(int(query.Page), int(query.Size)))

	//把数据封装到any里
	var models []*entity.PmsCategoryBrandRelation

	//直接拼接所有条件
	model := query.Model.(*entity.PmsCategoryBrandRelation)

	//count不包含limit条件
	var count int64
	tx.Model(&model).Count(&count)

	err := tx.Where(model).Find(&models).Error
	if err != nil {
		return nil, 0, err
	}
	return models, count, nil
}

func (this *pmsCategoryBrandRelationDao) DeleteById(db *gorm.DB, id int64) error {
	tx := db.Delete(&entity.PmsCategoryBrandRelation{}, id)
	if tx.Error != nil {
		return errors.New("无效删除")
	}
	return nil
}
func (this *pmsCategoryBrandRelationDao) UpdateById(db *gorm.DB, id int64, model *entity.PmsCategoryBrandRelation) error {
	model.Id = id
	tx := db.Updates(model)
	if tx.Error != nil {
		return errors.New("无效更新")
	}
	return nil
}

func (this *pmsCategoryBrandRelationDao) UpdateBrand(db *gorm.DB, brandId int64, brandName string) error {
	err := db.Table("pms_category_brand_relation").
		Where("brand_id=?", brandId).
		Update("brand_name", brandName).Error
	if err != nil {
		return errors.New("无效更新")
	}
	return nil
}

// UpdateCategory 更新Category列,这里因为涉及到事务,需要把begin返回回去
func (this *pmsCategoryBrandRelationDao) UpdateCategory(db *gorm.DB, cateLogId int64, cateLogName string) error {
	err := db.Table("pms_category_brand_relation").
		Where("catelog_id=?", cateLogId).
		Update("catelog_name", cateLogName).Error
	if err != nil {
		return errors.New("无效更新")
	}
	return nil
}

func (this *pmsCategoryBrandRelationDao) Save(db *gorm.DB, model *entity.PmsCategoryBrandRelation) (*entity.PmsCategoryBrandRelation, error) {
	tx := db.Create(model)
	if tx.RowsAffected == 0 {
		return nil, errors.New("保存失败")
	}
	return model, nil
}

func (this *pmsCategoryBrandRelationDao) FindByBrandId(db *gorm.DB, id int64) ([]*entity.PmsCategoryBrandRelation, error) {
	var models []*entity.PmsCategoryBrandRelation
	db.Where("brand_id=?", id).Find(&models)
	if len(models) == 0 {
		return nil, errors.New("无此关联")
	}
	return models, nil
}

func (this *pmsCategoryBrandRelationDao) FindBrandsBycateId(db *gorm.DB, id int64) ([]*entity.PmsCategoryBrandRelation, error) {
	var models []*entity.PmsCategoryBrandRelation
	db.Where("catelog_id=?", id).Find(&models)
	if len(models) == 0 {
		return nil, errors.New("无此关联")
	}
	return models, nil
}
